package com.bs.service;


import com.bs.domain.ServiceInfo;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class PartitionDashService {


    @Autowired
    ElasticsearchTemplate elasticsearchTemplate;

    private String partition;
    private String startTime;
    private String endTime;
    private Long interval;
    private String code;


    //服务调用
    private SearchResponse getCallServiceResponse() {
        String index = "logstash-" + code + "-svcsql-*";
        Client transportClient = elasticsearchTemplate.getClient();
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        builder.must(QueryBuilders.matchPhrasePrefixQuery("logmsg", "4. service end."));
        builder.filter(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("partition", partition))
            .must(QueryBuilders.termQuery("category", "SVCSQL"))
            .must(QueryBuilders.rangeQuery("@timestamp").from(startTime).to(endTime).timeZone("+08:00")));
        SearchRequestBuilder searchRequestBuilder = transportClient.prepareSearch(index).setTypes("log");
        DateHistogramBuilder timeAgg = AggregationBuilders.dateHistogram("date_histogram").field("@timestamp").interval(interval).minDocCount(1);


        return searchRequestBuilder
            .setSize(0)
            .setQuery(builder)
            .addAggregation(timeAgg)
            .execute().actionGet();
    }

    public List<ServiceInfo> callServiceResource(String partition, String startTime, String endTime, long interval, String code) {
        this.partition = partition;
        this.startTime = startTime;
        this.endTime = endTime;
        this.interval = interval;
        this.code = code;

        List<ServiceInfo> serviceInfoList = new ArrayList<>();
        SearchResponse response = getCallServiceResponse();
        if (response.getHits().totalHits() != 0) {
            Histogram agg = response.getAggregations().get("date_histogram");
            for (Histogram.Bucket entry : agg.getBuckets()) {
                String keyAsString = entry.getKeyAsString(); // Key as String
                long docCount = entry.getDocCount();         // Doc count
                ServiceInfo serviceInfo = new ServiceInfo(keyAsString, docCount);
                serviceInfoList.add(serviceInfo);
            }
        }
        return serviceInfoList;

    }

    // 异步路由发送
    private SearchResponse getCommSendResponse() {
        String index = "logstash-" + code + "-comm-*";
        Client transportClient = elasticsearchTemplate.getClient();
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        builder.filter(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("partition", partition))
            .must(QueryBuilders.termQuery("progress", "SRC->XCOM_WRITE_SEND"))
            .must(QueryBuilders.rangeQuery("@timestamp").from(startTime).to(endTime).timeZone("+08:00")));
        SearchRequestBuilder searchRequestBuilder = transportClient.prepareSearch(index).setTypes("log");
        DateHistogramBuilder timeAgg = AggregationBuilders.dateHistogram("date_histogram").field("@timestamp").interval(interval).minDocCount(1);


        return searchRequestBuilder
            .setSize(0)
            .setQuery(builder)
            .addAggregation(timeAgg)
            .execute().actionGet();
    }

    public List<ServiceInfo> commSendResource(String partition, String startTime, String endTime, long interval, String code) {
        this.partition = partition;
        this.startTime = startTime;
        this.endTime = endTime;
        this.interval = interval;
        this.code = code;
        List<ServiceInfo> serviceInfoList = new ArrayList<>();
        SearchResponse response = getCommSendResponse();
        System.out.println(response.getHits().totalHits());
        if (response.getHits().totalHits() != 0) {
            Histogram agg = response.getAggregations().get("date_histogram");
            for (Histogram.Bucket entry : agg.getBuckets()) {
                String keyAsString = entry.getKeyAsString(); // Key as String
                long docCount = entry.getDocCount();         // Doc count
                ServiceInfo serviceInfo = new ServiceInfo(keyAsString, docCount);
                serviceInfoList.add(serviceInfo);
            }
        }
        return serviceInfoList;

    }

    //电文发送
    private SearchResponse getTeleSendResponse() {
        String index = "logstash-" + code + "-*";
        Client transportClient = elasticsearchTemplate.getClient();
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        builder.must(QueryBuilders.matchPhrasePrefixQuery("logmsg", "EPEX: Begin to call EDSendWithHd"));
        builder.filter(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("partition", partition))
            .must(QueryBuilders.termQuery("func", "TEL"))
            .must(QueryBuilders.rangeQuery("@timestamp").from(startTime).to(endTime).timeZone("+08:00")));
        SearchRequestBuilder searchRequestBuilder = transportClient.prepareSearch(index).setTypes("log");
        DateHistogramBuilder timeAgg = AggregationBuilders.dateHistogram("date_histogram").field("@timestamp").interval(interval).minDocCount(1);

        return searchRequestBuilder
            .setSize(0)
            .setQuery(builder)
            .addAggregation(timeAgg)
            .execute().actionGet();
    }

    public List<ServiceInfo> teleSendResource(String partition, String startTime, String endTime, long interval, String code) {
        this.partition = partition;
        this.startTime = startTime;
        this.endTime = endTime;
        this.interval = interval;
        this.code = code;
        List<ServiceInfo> serviceInfoList = new ArrayList<>();
        SearchResponse response = getTeleSendResponse();
        if (response.getHits().totalHits() != 0) {
            Histogram agg = response.getAggregations().get("date_histogram");
            for (Histogram.Bucket entry : agg.getBuckets()) {
                String keyAsString = entry.getKeyAsString(); // Key as String
                long docCount = entry.getDocCount();         // Doc count
                ServiceInfo serviceInfo = new ServiceInfo(keyAsString, docCount);
                serviceInfoList.add(serviceInfo);
            }
        }
        return serviceInfoList;

    }

    //批作业调用
    private SearchResponse getCallBatchResponse() {
        String index = "logstash-" + code + "-svcsql-*";
        Client transportClient = elasticsearchTemplate.getClient();
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        builder.must(QueryBuilders.matchPhrasePrefixQuery("logmsg", "2. batch"));
        builder.filter(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("partition", partition))
            .must(QueryBuilders.termQuery("category", "SVCSQL"))
            .must(QueryBuilders.rangeQuery("@timestamp").from(startTime).to(endTime).timeZone("+08:00")));
        SearchRequestBuilder searchRequestBuilder = transportClient.prepareSearch(index).setTypes("log");
        DateHistogramBuilder timeAgg = AggregationBuilders.dateHistogram("date_histogram").field("@timestamp").interval(interval).minDocCount(1);

        return searchRequestBuilder
            .setSize(0)
            .setQuery(builder)
            .addAggregation(timeAgg)
            .execute().actionGet();
    }

    public List<ServiceInfo> callBatchResource(String partition, String startTime, String endTime, long interval, String code) {
        this.partition = partition;
        this.startTime = startTime;
        this.endTime = endTime;
        this.interval = interval;
        this.code = code;
        List<ServiceInfo> serviceInfoList = new ArrayList<>();
        SearchResponse response = getCallBatchResponse();
        if (response.getHits().totalHits() != 0) {
            Histogram agg = response.getAggregations().get("date_histogram");
            for (Histogram.Bucket entry : agg.getBuckets()) {
                String keyAsString = entry.getKeyAsString(); // Key as String
                long docCount = entry.getDocCount();         // Doc count
                ServiceInfo serviceInfo = new ServiceInfo(keyAsString, docCount);
                serviceInfoList.add(serviceInfo);
            }
        }
        return serviceInfoList;

    }


    //异步路由接收
    private SearchResponse getCommReceiveResourceResponse() {
        String index = "logstash-" + code + "-comm-*";
        Client transportClient = elasticsearchTemplate.getClient();
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        builder.filter(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("partition", partition))
            .must(QueryBuilders.termQuery("category", "COMM"))
            .must(QueryBuilders.termQuery("progress_seq", "500"))
            .mustNot(QueryBuilders.termQuery("uuid", "<NULL-GUID>"))
            .must(QueryBuilders.rangeQuery("@timestamp").from(startTime).to(endTime).timeZone("+08:00")));
        SearchRequestBuilder searchRequestBuilder = transportClient.prepareSearch(index).setTypes("log");
        DateHistogramBuilder timeAgg = AggregationBuilders.dateHistogram("date_histogram").field("@timestamp").interval(interval).minDocCount(1);

        return searchRequestBuilder
            .setSize(0)
            .setQuery(builder)
            .addAggregation(timeAgg)
            .execute().actionGet();
    }

    public List<ServiceInfo> commReceiveResource(String partition, String startTime, String endTime, long interval, String code) {
        this.partition = partition;
        this.startTime = startTime;
        this.endTime = endTime;
        this.interval = interval;
        this.code = code;
        List<ServiceInfo> serviceInfoList = new ArrayList<>();
        SearchResponse response = getCommReceiveResourceResponse();
        if (response.getHits().totalHits() != 0) {
            Histogram agg = response.getAggregations().get("date_histogram");
            for (Histogram.Bucket entry : agg.getBuckets()) {
                String keyAsString = entry.getKeyAsString(); // Key as String
                long docCount = entry.getDocCount();         // Doc count
                ServiceInfo serviceInfo = new ServiceInfo(keyAsString, docCount);
                serviceInfoList.add(serviceInfo);
            }
        }
        return serviceInfoList;

    }

    //电文接收
    private SearchResponse getTeleReceiveResourceResponse() {
        String index = "logstash-" + code + "-comm-*";
        Client transportClient = elasticsearchTemplate.getClient();
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        builder.must(QueryBuilders.matchPhrasePrefixQuery("logmsg", "Routing-async called-service begin"));
        builder.filter(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("partition", partition))
            .must(QueryBuilders.boolQuery()
                .should(QueryBuilders.termQuery("_missing_", "uuid"))
                .should(QueryBuilders.termQuery("uuid", "<NULL-GUID>")))
            .must(QueryBuilders.rangeQuery("@timestamp").from(startTime).to(endTime).timeZone("+08:00")));
        SearchRequestBuilder searchRequestBuilder = transportClient.prepareSearch(index).setTypes("log");
        DateHistogramBuilder timeAgg = AggregationBuilders.dateHistogram("date_histogram").field("@timestamp").interval(interval).minDocCount(1);


        return searchRequestBuilder
            .setSize(0)
            .setQuery(builder)
            .addAggregation(timeAgg)
            .execute().actionGet();
    }

    public List<ServiceInfo> teleReceiveResource(String partition, String startTime, String endTime, long interval, String code) {
        this.partition = partition;
        this.startTime = startTime;
        this.endTime = endTime;
        this.interval = interval;
        this.code = code;
        List<ServiceInfo> serviceInfoList = new ArrayList<>();
        SearchResponse response = getTeleReceiveResourceResponse();
        if (response.getHits().totalHits() != 0) {
            Histogram agg = response.getAggregations().get("date_histogram");
            for (Histogram.Bucket entry : agg.getBuckets()) {
                String keyAsString = entry.getKeyAsString(); // Key as String
                long docCount = entry.getDocCount();         // Doc count
                ServiceInfo serviceInfo = new ServiceInfo(keyAsString, docCount);
                serviceInfoList.add(serviceInfo);
            }
        }
        return serviceInfoList;
    }

}
